package com.lvmama.pet.sync.service;

import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;

import com.lvmama.comm.bee.service.sync.SyncDataSourceService;
import com.lvmama.comm.bee.service.sync.SyncNewException;
import com.lvmama.comm.sync.po.SyncDataSource;
import com.lvmama.pet.sync.dao.SyncDataSourceMapper;

public class SyncDataSourceServiceImpl implements SyncDataSourceService{

	@Autowired
	private SyncDataSourceMapper syncDataSourceMapper;
	@Override
	public void save(SyncDataSource syncDataSource) {
		List<SyncDataSource> list = syncDataSourceMapper.findBySourceCode(syncDataSource.getSourceCode());
		if(null!=list&&list.size()>0){
			throw new SyncNewException("数据源已存在,请重新输入code!");
		}
		 syncDataSourceMapper.save(syncDataSource);
		 //数据源添加到map
		 SyncBaseExecuteServiceImpl.addDataSource(syncDataSource);
	}

	@Override
	public List<SyncDataSource> findAll() {
		return syncDataSourceMapper.findAll();
	}

	@Override
	public List<SyncDataSource> findBySourceCode(String sourceCode) {

		return syncDataSourceMapper.findBySourceCode(sourceCode);
	}

	@Override
	public Long count(Map<String,Object> parmas) {
		
		return syncDataSourceMapper.count(parmas);
	}

	@Override
	public List<SyncDataSource> findPageListByCondition(Map<String,Object> param) {

		return syncDataSourceMapper.findPageListByCondition(param);
	}

	@Override
	public void update(SyncDataSource syncDataSource) {
		Boolean flag = false;
		SyncDataSource _syncDataSource = syncDataSourceMapper.findById(syncDataSource.getSourceId());
		if(_syncDataSource.getSourceCode().equals(syncDataSource.getSourceCode())){
			flag= true;
		}else{
			List<SyncDataSource> list = syncDataSourceMapper.findBySourceCode(syncDataSource.getSourceCode());
			
			if(null!=list&&list.size()>0){
				
				throw new SyncNewException("数据源已存在,请重新输入code!");
			}else{
				flag = true;
			}
		}
		if(flag){
			 syncDataSource.setPassword(syncDataSource.getPassword().trim());
			 syncDataSourceMapper.update(syncDataSource);
			 if(StringUtils.isEmpty(syncDataSource.getPassword().trim())){
				 syncDataSource.setPassword(syncDataSourceMapper.findById(syncDataSource.getSourceId()).getPassword());
			 }
			//数据源添加到map
			 SyncBaseExecuteServiceImpl.addDataSource(syncDataSource);
		}
		
	}

	@Override
	public SyncDataSource findById(Long sourceId) {
		return syncDataSourceMapper.findById(sourceId);
	}

	@Override
	public void deleteById(Long sourceId) {

		syncDataSourceMapper.deleteById(sourceId);
	}
		
}
